package com.whoami.idmagic.api;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.hbase.filter.RandomRowFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tzp
 * @since 2019/8/26
 */
@Controller
public class HelloController {
    @Autowired
    HBaseConnection hBaseConnection;
    @Value("${data.tablename}")
    private String tableName;
    @Value("${data.family}")
    private String cfDefault;
    @Value("${data.random}")
    private float randomChange;

    @GetMapping("/get")
    @ResponseBody
    public Map get(@RequestParam("key") String key) {
        Connection connection = hBaseConnection.getConnection();
        HashMap<String, String> result = new HashMap<>(2);
        try {
            Table table = connection.getTable(TableName.valueOf(tableName));
            Get get = new Get(key.getBytes());
            Result cell = table.get(get);
            byte[] value = cell.getValue(cfDefault.getBytes(), null);

            result.put("key", key);
            result.put("value", Bytes.toString(value));
        } catch (IOException e) {
            e.printStackTrace();
        }
            return result;
    }

    @GetMapping("/random")
    @ResponseBody
    public Map rand() {
        Connection connection = hBaseConnection.getConnection();
        HashMap<String, String> result = new HashMap<>(2);
        try {
            Table table = connection.getTable(TableName.valueOf(tableName));

            FilterList list = new FilterList();
            RandomRowFilter randomRowFilter = new RandomRowFilter(randomChange);
            PageFilter pageFilter = new PageFilter(1);
            list.addFilter(randomRowFilter);
            list.addFilter(pageFilter);

            Scan scan = new Scan();
//            scan.addFamily()
            scan.setFilter(list);

            ResultScanner scanner = table.getScanner(scan);

            Result next = scanner.next();

            result.put("key", Bytes.toString(next.getRow()));
            result.put("value", Bytes.toString(next.getValue(cfDefault.getBytes(), null)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
